<template>
  <div class="xq-form-wrapper rmt">
    <a-row type="flex" align="middle" justify="space-between">
      <a-col>
        <a-select placeholder="选择企业" v-model="companyUnitId" allowClear class="mr12" style="width: 180px" @change="handleChange">
          <a-select-option :value="item.id" v-for="item in companyUnitIdArr" :key="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
        <a-input-search allowClear v-model="positionName" placeholder="搜索职位" class="mr12" style="width: 180px" @search="onSearch" />
        <a-select mode="multiple" placeholder="职位类型" v-model="queryRecruitType" allowClear style="width: 250px" @change="handleChange">
          <a-select-option :value="item.id" v-for="item in queryRecruitTypeArr" :key="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-col>
      <a-col>
        <!-- <a-button style="margin-right:12px;" @click="onAll">
          批量操作
        </a-button> -->
        <a-button type="primary" class="mr12" @click="generateLink">生成招聘小程序链接</a-button>
        <a-button class="mr12" v-if="isCancel === '2'" @click="resumeDeliverySettings">
          <span style="padding-right: 6px" class="icon iconfont">&#xe61d;</span> 投递简历设置
        </a-button>
        <a-button class="mr12" v-if="isCancel === '2'" :disabled="!selectedRowKeys.length" @click="onAllShare"> 生成岗位链接 </a-button>
        <a-button type="primary" @click="onAdd">
          <a-icon type="plus" style="font-size: 14px" />
          发布职位
        </a-button>
      </a-col>
    </a-row>
    <a-alert type="info" class="glinfo" closable>
      <p slot="description">
        <a-icon type="exclamation-circle" theme="filled" style="color: #4686ff; margin-right: 2px" />
        快速创建
        <a @click="onJump('economic', 'position')">经纪人岗位</a> 和
        <a @click="onJump('push', 'position')">内推岗位</a>
      </p>
    </a-alert>
    <a-spin :spinning="spinning" class="xq-form-content" style="margin-top: 16px">
      <XqTable
        :customize="FormJson['config']['table']['customize']"
        :scroll="{ x: columns.length * 150 }"
        :pagination="false"
        :dataSource="tableData"
        :columns="columns"
        class="xq-form-content-table"
        :rowSelection="
          FormJson['config']['table']['extend']['batch']
            ? {
                selectedRowKeys: selectedRowKeys,
                onChange: onSelectChange,
                getCheckboxProps: (record) => ({
                  props: {
                    disabled: record.companyUnitsVO === null
                  }
                })
              }
            : null
        "
      >
        <!-- eslint-disable-next-line prettier/prettier -->
        <template v-for="(col, index) in columns" v-slot:[col.dataIndex]="text, record">
          <div v-if="col.dataIndex === 'postName'" :key="index" class="table-col">
            <div class="table-name" @click="showUpdateModal(record)">
              <a-tooltip placement="top">
                <template slot="title" v-if="record.postName">
                  <span>{{ record.postName }}</span>
                </template>
                <div class="table-postName">{{ record.postName }}</div>
              </a-tooltip>

              <div class="t-status isEmergency" v-if="record.isEmergency">急</div>
              <div class="t-status isEmp" v-if="record.isEmp === 1">内推</div>
              <div class="t-status isBroker" v-if="record.isBroker === 1">经纪人</div>
            </div>
            <div class="table-desc mb12" style="text-align: left" v-if="record.cityName.split(',')[1]">
              {{ record.cityName.split(",")[1].split("/").join("-") }}
              /
              <span v-if="record.workingSeniority === 1">不限</span>
              <span v-if="record.workingSeniority === 2">应届生</span>
              <span v-if="record.workingSeniority === 3">1-3年</span>
              <span v-if="record.workingSeniority === 4">3-5年</span>
              <span v-if="record.workingSeniority === 5">5-10年</span>
              <span v-if="record.workingSeniority === 6">10年以上</span>
              /
              <span v-if="record.lowestEducation === 1">初中</span>
              <span v-if="record.lowestEducation === 2">中专</span>
              <span v-if="record.lowestEducation === 3">大专</span>
              <span v-if="record.lowestEducation === 4">高中</span>
              <span v-if="record.lowestEducation === 5">本科</span>
              <span v-if="record.lowestEducation === 6">硕士</span>
              <span v-if="record.lowestEducation === 7">博士</span>
              <span v-if="record.lowestEducation === 8">其他</span>
              <span>以上/</span>
              <span>
                <span v-if="record.highestSalary === record.lowestSalary">{{ record.highestSalary | nFormatter }}元</span>
                <span v-else>{{ record.lowestSalary | nFormatter }} - {{ record.highestSalary | nFormatter }}元</span> </span
              >/
              <span v-if="record.salaryGrantType == 0">小时</span>
              <span v-if="record.salaryGrantType == 1">日</span>
              <span v-if="record.salaryGrantType == 2">月</span>
              <span v-if="record.salaryGrantType == 3">年</span>
            </div>
            <a-tooltip placement="bottom">
              <template slot="title" v-if="record.companyUnitsVO">
                <span>{{ record.companyUnitsVO.name }}</span>
              </template>
              <div class="table-desc companyUnitsVOName" style="text-align: left">
                {{ record.companyUnitsVO != null ? record.companyUnitsVO.name : "企业已删除" }}
              </div>
            </a-tooltip>
          </div>
          <div class="table-col table-col-hover" v-if="col.dataIndex === 'candidateCount'" :key="index" @click="onView(record.id, '1')">
            <div class="table-status-t">
              {{ record.candidateCount }}
            </div>
            <div class="table-desc">
              {{ col.customTitle }}
            </div>
          </div>
          <div class="table-col table-col-hover" v-if="col.dataIndex === 'faceToFaceCount'" :key="index" @click="onView(record.id, '2')">
            <div class="table-status-t">
              {{ record.faceToFaceCount }}
            </div>
            <div class="table-desc">
              {{ col.customTitle }}
            </div>
          </div>
          <div class="table-col table-col-hover" v-if="col.dataIndex === 'toBeEmployedCount'" :key="index" @click="onView(record.id, '3')">
            <div class="table-status-t">
              {{ record.toBeEmployedCount }}
            </div>
            <div class="table-desc">
              {{ col.customTitle }}
            </div>
          </div>
          <div class="table-col table-col-hover" v-if="col.dataIndex === 'recruitedCount'" :key="index" @click="onView(record.id, '4')">
            <div class="table-status-t">
              {{ record.recruitedCount }}
            </div>
            <div class="table-desc">
              {{ col.customTitle }}
            </div>
          </div>
          <div class="table-col table-col-hover" v-if="col.dataIndex === 'failCount'" :key="index" @click="onView(record.id, '5')">
            <div class="table-status-t">
              {{ record.failCount }}
            </div>
            <div class="table-desc">
              {{ col.customTitle }}
            </div>
          </div>
          <div v-if="col.dataIndex === 'gmtCreate'" :key="index" class="table-col" style="text-align: center">
            <div class="table-desc" style="color: #a6a8b4; margin-top: 40px">{{ moment(record.gmtCreate).format("YYYY-MM-DD") }} 发布</div>
          </div>

          <div v-if="col.dataIndex === 'tableAction'" :key="index" class="table-col" style="border-right: 1px solid #e8e8e8">
            <div style="border-radius: 4px 0 0 4px; margin-top: 40px; text-align: center">
              <a @click="showUpdateModal(record)">详情</a>
              <a-divider type="vertical" />
              <a-popconfirm
                :disabled="record.companyUnitsVO === null"
                :title="`确认要${isCancel === '2' ? '关闭' : '打开'}吗？`"
                ok-text="确认"
                cancel-text="取消"
                @confirm="close(record.id)"
              >
                <a :disabled="record.companyUnitsVO === null">{{ isCancel === "2" ? "关闭" : "打开" }}</a>
              </a-popconfirm>
              <!-- <a-popconfirm v-if="isCancel === 2" :title="`确认要关闭吗？`" ok-text="确认" cancel-text="取消" @confirm="close(record.id)">
              <a>关闭</a>
            </a-popconfirm>
            <a-popconfirm v-if="isCancel === 1" :title="`确认要打开吗？`" ok-text="确认" cancel-text="取消" @confirm="close(record.id)">
              <a>打开</a>
            </a-popconfirm> -->
              <a-divider type="vertical" v-if="isCancel === '2'" />
              <a v-if="isCancel === '2'" @click="onShare(record.id)">分享</a>
            </div>
          </div>
        </template>
      </XqTable>
      <div class="xq-form-content-pagination">
        <div class="xq-form-content-pagination-total">共 {{ total }} 条</div>
        <a-pagination
          v-model="pageNo"
          :total="total"
          :show-size-changer="true"
          :show-quick-jumper="true"
          :page-size-options="['10', '20', '50', '100']"
          :page-size="pageSize"
          @change="onPageChange"
          @showSizeChange="onPageSizeChange"
        />
      </div>
    </a-spin>
    <div class="r-table-footer" v-if="selectedRowKeys.length > 0">
      <div>
        选中职位&nbsp;&nbsp; {{ selectedRowKeys.length }} 个 &nbsp;&nbsp;&nbsp;&nbsp;
        <a-button type="link" @click="selectedRowKeys = []"> 清除 </a-button>
      </div>
      <div>
        <a-button type="primary" @click="allClose('打开')" v-if="isCancel === '1'" style="margin-right: 12px">打开职位</a-button>
        <a-button type="primary" @click="allClose('关闭')" v-if="isCancel === '2'" style="margin-right: 12px">关闭职位</a-button>
      </div>
    </div>
    <share :visible.sync="visible" :shareIdArr="shareIdArr" shareType="poster" />
  </div>
</template>

<script>
import FormJson from "./FormJson";
import XqCurdMixin from "xqjr-plugin-form/mixins/XqCurdMixin";
import { getRecruitInfos, putCancelBatch, getCompanyUnits, getSharePositionByH5Req } from "../api";
import share from "../../component/share";
import moment from "moment";

const curdMixin = new XqCurdMixin({
  FormJson,
  tableConfigKey: "table"
});
export default {
  mixins: [curdMixin],
  components: {
    share
  },
  props: {
    isCancel: {
      type: String,
      default: "2"
    }
  },
  watch: {
    isCancel() {
      this.onGetRecruitInfos();
    }
  },
  data() {
    return {
      visible: false,
      spinning: false,
      tableData: [],
      total: 0,
      pageNo: 1,
      pageSize: 20,
      selectedRowKeys: [],
      shareIdArr: [],
      companyUnitIdArr: [],
      queryRecruitTypeArr: [
        { id: 1, name: "普通" },
        { id: 2, name: "经纪人" },
        { id: 3, name: "内推" }
      ],
      companyUnitId: undefined,
      positionName: "",
      queryRecruitType: undefined
    };
  },
  created() {
    this.onGetRecruitInfos();
    this.onGetCompanyUnits();
  },
  mounted() {
    const dom = document.querySelector(".ant-table-selection-column");
    dom.setAttribute("width", 100);
    const $el = document.createElement("div");
    $el.textContent = "全选当页";
    dom.insertBefore($el, dom.children[0]);
  },
  filters: {
    nFormatter(num, digits = 2) {
      const si = [
        { value: 1, symbol: "" },
        { value: 1e3, symbol: "k" },
        { value: 1e4, symbol: "w" }
        // { value: 1e9, symbol: "g" },
        // { value: 1e12, symbol: "T" },
        // { value: 1e15, symbol: "P" },
        // { value: 1e18, symbol: "E" }
      ];
      const rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
      let i;
      for (i = si.length - 1; i > 0; i--) {
        if (num >= si[i].value) {
          break;
        }
      }
      return (num / si[i].value).toFixed(digits).replace(rx, "$1") + si[i].symbol;
    }
  },
  methods: {
    generateLink() {
      getSharePositionByH5Req()
        .then((res) => {
          console.log(res);
          if (res && res.code === 200) {
            this.$copyText(res.data)
              .then(() => {
                this.$message.success("链接已到黏贴版");
              })
              .catch(() => {
                this.$message.error("复制错误");
              });
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          console.log("getSharePositionByH5Req", err);
        });
    },
    moment,
    resumeDeliverySettings() {
      this.$router.push({ name: "resumeeliverySettings" });
    },
    async onGetRecruitInfos() {
      try {
        this.visible = false;
        this.spinning = true;
        const { data } = await getRecruitInfos({
          companyUnitId: this.companyUnitId || "",
          positionName: this.positionName,
          isCancel: this.isCancel,
          queryRecruitType: this.queryRecruitType,
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          "orders[0].property": "gmtCreate",
          "orders[0].desc": true
        });
        this.tableData = data.entities;
        this.total = data.entityCount;
        setTimeout(() => (this.spinning = false), 500);
      } catch (err) {
        console.log("error log --> ", err);
        this.tableData = [];
        this.total = 0;
        setTimeout(() => (this.spinning = false), 500);
      }
    },
    async onGetCompanyUnits() {
      try {
        const { data } = await getCompanyUnits({
          pageNo: 1,
          pageSize: 1000
        });
        this.companyUnitIdArr = data.entities;
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    onPageChange(page) {
      this.pageNo = page;
      this.selectedRowKeys = [];
      this.onGetRecruitInfos();
    },
    onPageSizeChange(current, pageSize) {
      if (this.pageNo !== 1) this.selectedRowKeys = [];
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.onGetRecruitInfos();
    },
    showUpdateModal(e) {
      this.$router.push({ name: "managementMsg", query: { id: e.id } });
    },
    handleChange() {
      this.pageNo = 1;
      this.onGetRecruitInfos();
    },
    onSearch() {
      this.pageNo = 1;
      this.onGetRecruitInfos();
    },
    onAll() {
      this.tableData.forEach((e) => {
        this.selectedRowKeys.push(e.id);
      });
      this.selectedRowKeys = Array.from(new Set(this.selectedRowKeys));
    },
    onSelectChange(e) {
      this.selectedRowKeys = e;
      // this.selectedRowKeys = Array.from(new Set([...this.selectedRowKeys, ...e]));
    },
    onAdd() {
      this.$router.push({ name: "managementAdd" });
    },
    onShare(e) {
      this.visible = true;
      this.shareIdArr = [e];
    },
    onAllShare() {
      this.shareIdArr = this.selectedRowKeys;
      this.visible = true;
    },
    allClose(v) {
      this.$confirm({
        okText: "确定",
        title: `确定要批量${v}？`,
        onOk: () => {
          const recruitInfoIds = this.selectedRowKeys;
          this.close(recruitInfoIds);
        }
      });
    },
    async close(e) {
      try {
        const data = {
          isCancel: this.isCancel === "1" ? 2 : 1,
          recruitInfoIds: e instanceof Array ? e : e.split(",")
        };

        await putCancelBatch(data);
        if (this.tableData.length === 1) {
          this.pageNo = 1;
        }
        this.$notification.success({
          message: "提示",
          description: "操作成功"
        });
        this.onGetRecruitInfos();
        this.selectedRowKeys = [];
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    onView(recruitInfoId, e) {
      this.$router.push({ name: "people", query: { status: e, recruitInfoId } });
    },
    onJump(name, toName) {
      this.$router.push({ name, query: { name: toName } });
    }
  }
};
</script>

<style lang="scss" scoped>
.rmt {
  ::v-deep .ant-table-thead {
    & > tr > th {
      background: #fff !important;
      border: 0;
      padding: 0;
      padding-left: 62px;
    }
    .ant-table-selection-column {
      position: relative;
      padding-bottom: 16px;
      & > div {
        position: absolute;
        left: 0;
        top: -2px;
      }
      & > span {
        display: block !important;
        height: 17px;
        line-height: 17px;
        border: 0 !important;
      }
    }
  }
  ::v-deep .ant-table-row-hover > td {
    background: #fff !important;
  }
  ::v-deep.ant-table-tbody > tr.ant-table-row-selected td {
    background: #fff !important;
  }
  ::v-deep .ant-table-selection-column > span {
    display: block;
    height: 146px;
    line-height: 146px;
    border: 1px solid #e8e8e8;
    border-right: 0;
    border-radius: 4px 0 0 4px;
  }
  ::v-deep .ant-table-row-cell-break-word {
    padding: 0 0 12px 0;
    border: 0;
  }
  ::v-deep .ant-table-tbody > tr > td {
    padding: 0 0 12px 0;
    border: 0;
  }
}
.table-col {
  height: 146px;
  padding: 24px 0;
  border-top: 1px solid #e8e8e8;
  border-bottom: 1px solid #e8e8e8;
}

// .table-col {
//   text-align: center;
//   cursor: pointer;
//   &:hover {
//     color: var(--primary) !important;
//   }
// }
// ::v-deep .ant-table-selection-column {
//   border-right: 0 !important;
//   margin-bottom: 12px;
// }
// ::v-deep .ant-table-bordered .ant-table-tbody > tr > td {
//   border-right: 0 !important;
//   margin-bottom: 12px;
// }
.r-table-footer {
  z-index: 999;
  width: calc(100vw - 188px);
  height: 56px;
  line-height: 56px;
  padding: 0 24px;
  background: #ffffff;
  box-shadow: 0px 2px 7px 0px rgba(0, 0, 0, 0.15);
  display: flex;
  justify-content: space-between;
  position: fixed;
  right: 0;
  bottom: 0;
}
.table-name {
  display: flex;
  font-size: 10px;
  line-height: 27px;
  cursor: pointer;
  .table-postName {
    max-width: 70%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-size: 18px;
    font-weight: 500;
    color: #3c3d43;
    margin-right: 8px;
    margin-bottom: 16px;
  }
  .t-status {
    height: 20px;
    line-height: 20px;
    border-radius: 2px;
    text-align: center;
    margin-top: 4px;
    margin-right: 8px;
  }
  .isEmergency {
    width: 26px;
    background: #ffa940;
    color: #fff;
  }
  .isEmp {
    width: 36px;
    border: 1px solid #32ccaa;
    color: #32ccaa;
  }
  .isBroker {
    width: 46px;
    border: 1px solid #4686ff;
    color: #4686ff;
  }
}
.table-col-hover {
  cursor: pointer;
  &:hover .table-desc {
    color: var(--primary);
  }
  &:hover .table-status-t {
    color: var(--primary);
  }
}
.table-desc {
  color: #767885;
  text-align: center;
}
.table-status-t {
  font-size: 18px;
  text-align: center;
  margin: 16px 0 10px 0;
}
.glinfo {
  padding: 4px 16px;
  height: 40px;
  margin-top: 16px;
  ::v-deep .ant-alert-close-icon {
    top: 10px !important;
  }
}
.companyUnitsVOName {
  max-width: 70%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
